from flask import Flask
from flask_script import Manager,Server
from flask_migrate import Migrate,MigrateCommand
from   views import bp
from models import db,Movies
import csv
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:root@192.168.6.66/movies'
app.register_blueprint(bp)
db.init_app(app)

migrate = Migrate(app,db=db,compare_type=True)
manager = Manager(app)
manager.add_command("db",MigrateCommand)
manager.add_command('server',Server(use_debugger=True))
# 添加一个初始化movies表数据的命令,读取movies.csv，写入到movies表中

@manager.command
def initdata():
    inpath = os.path.abspath( "../data/movies.csv")

    print("使用{}初始化movies表.".format(inpath))
    with open(inpath,"r",encoding='UTF8') as file:
        reader  = csv.DictReader(file)
        for line in reader:
            print(line)
            movie = Movies(**line)
            db.session.add(movie)
    db.session.commit()

if __name__=="__main__":
    manager.run(default_command="server")





